package org.jeecg.modules.flow.activiti.listener;

import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.delegate.DelegateTask;
import org.activiti.engine.delegate.event.ActivitiEvent;
import org.activiti.engine.delegate.event.ActivitiEventListener;
import org.activiti.engine.delegate.event.impl.ActivitiEntityEventImpl;
import org.activiti.engine.delegate.event.impl.ActivitiProcessCancelledEventImpl;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.impl.persistence.entity.ExecutionEntity;
import org.activiti.engine.impl.persistence.entity.TaskEntity;
import org.activiti.engine.runtime.ProcessInstance;
import org.jeecg.modules.flow.service.FlowEventMsgService;
import org.jeecg.modules.flow.service.IFlowPermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 流程全局事件监听器
 */
@Component
@Slf4j
public class GlobalEventListener implements ActivitiEventListener {

    @Autowired
    @Lazy
    private FlowEventMsgService flowEventMsgService;

    @Resource
    @Lazy
    private HistoryService historyService;

    @Autowired
    @Lazy
    private IFlowPermissionService flowPermissionService;

    @Resource
    @Lazy
    private RuntimeService runtimeService;

    @Override
    public void onEvent(ActivitiEvent event) {
        switch (event.getType()) {
            case ENTITY_CREATED:
                log.info("实体创建事件");
                entityCreate(event);
                break;
            case ENTITY_DELETED:
                log.info("实体删除事件");
                break;
            case ENTITY_SUSPENDED:
                log.info("实体暂停事件");
                break;
            case ENTITY_ACTIVATED:
                log.info("实体激活事件");
                break;
            case TASK_CREATED:
                log.info("任务创建事件");
                //taskCreate(event);
                break;
            case TASK_COMPLETED:
                log.info("任务完成事件");
                //taskCompleted(event);
                break;
            case PROCESS_COMPLETED:
                // 发送流程结束消息
                processCompleted(event);
                break;
            case PROCESS_CANCELLED:
                log.info("任务终止事件");
                processCancelled(event);
                break;

        }
    }

    /**
     * 实体被创建事件
     *
     * @param event
     */
    private void entityCreate(ActivitiEvent event) {

    }


    /**
     * 任务创建时触发
     *
     * @param event
     */
    public void taskCreate(ActivitiEvent event) {
        ActivitiEntityEventImpl eventImpl = (ActivitiEntityEventImpl) event;
        DelegateTask delegateTask = (DelegateTask) eventImpl.getEntity();
        flowPermissionService.setUserTaskPermission(delegateTask);
        //判断是否设置了任务完成时发送消息  是否需要发送消息 若需要 则发送消息
    }


    /**
     * 任务完成时触发
     *
     * @param event
     */
    public void taskCompleted(ActivitiEvent event) {
        ActivitiEntityEventImpl eventImpl = (ActivitiEntityEventImpl) event;
        TaskEntity entity = (TaskEntity) eventImpl.getEntity();
        ProcessInstance instance = runtimeService.createProcessInstanceQuery()
                .processInstanceId(entity.getProcessInstanceId())
                .singleResult();
        if (instance != null) {
            flowEventMsgService.sendTaskCompletedMsg(event.getProcessInstanceId(), entity.getId(), instance.getBusinessKey());
        }

    }

    /**
     * 流程正常结束时触发
     *
     * @param event
     */
    public void processCompleted(ActivitiEvent event) {
        ActivitiEntityEventImpl eventImpl = (ActivitiEntityEventImpl) event;
        ExecutionEntity entity = (ExecutionEntity) eventImpl.getEntity();
        // 发送流程完成消息
        flowEventMsgService.sendProcessCompletedMsg(entity.getProcessInstanceId(), entity.getBusinessKey());
    }

    /**
     * 流程终止时触发
     *
     * @param event
     */
    public void processCancelled(ActivitiEvent event) {
        ActivitiProcessCancelledEventImpl eventImpl = (ActivitiProcessCancelledEventImpl) event;
        HistoricProcessInstance hpi = historyService.createHistoricProcessInstanceQuery()
                .processInstanceId(eventImpl.getProcessInstanceId()).singleResult();
        if (hpi != null) {
            //发送流程终止消息
            flowEventMsgService.sendProcessCancelledMsg(eventImpl.getProcessInstanceId(), hpi.getBusinessKey());
        }
    }


    @Override
    public boolean isFailOnException() {
        log.info("listener 异常");
        return false;
    }

}
